package com.quectel.cms.controller.home;


import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.business.common.util.sys.SysCodeUtils;
import com.quectel.cms.controller.BaseController;
import com.quectel.cms.controller.grid.helper.GridHelper;
import com.quectel.cms.util.SessionHolder;
import com.quectel.cms.vo.home.CommonCountResp;
import com.quectel.cms.vo.home.CommonPieResp;
import com.quectel.cms.vo.home.GridEventStatusCountResp;
import com.quectel.cms.vo.home.GridEventTypeCountResp;
import com.quectel.constant.core.grid.GridConstant;
import com.quectel.constant.global.StatisticsConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.sys.SysCodeKeyConstants;
import com.quectel.core.module.grid.dto.*;
import com.quectel.core.module.grid.service.*;
import com.quectel.util.common.Page;
import com.quectel.util.common.Request;
import com.quectel.util.common.Response;
import com.quectel.util.thread.ThreadPoolUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author zhangheng
 * @email nolan.zhang@quectel.com
 * @date 2023/02/17 16:42
 */
@RestController
@RequestMapping("home/grid")
@Tag(name = "HomeGridController", description = "网格网页相关api")
@Slf4j
public class HomeGridController extends BaseController {

    @DubboReference
    private GridNoticeService gridNoticeService;
    @DubboReference
    private GridNoticeRelationService gridNoticeRelationService;
    @DubboReference
    private GridEventRecordService gridEventRecordService;

    @DubboReference
    private GridPrimaryEventService gridPrimaryEventService;

    @DubboReference
    private GridSecondaryEventService gridSecondaryEventService;

    @Autowired
    private GridHelper gridHelper;

    private static final ThreadPoolExecutor executorService = ThreadPoolUtils.createCommonIOBoundPool("gird_home_pool");


    /**
     * 上级通知列表
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("parentNoticeList")
    @Operation(summary = "上级通知列表")
    public Response<Page<GridNoticeRelationDto>> parentNoticeList(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());

        //查询当前用户组级别
        List<GridRegionInfoDto> gridRegionInfoDtos = gridHelper.queryRegionInfoByGroupId(SessionHolder.getSysUser().getGroupId());

        if (CollectionUtils.isEmpty(gridRegionInfoDtos)) {
            Page<GridNoticeRelationDto> page = new Page<>(request.getPageNo(), request.getPageSize(), 0, Collections.emptyList());
            return Response.<Page<GridNoticeRelationDto>>ok().wrap(page);
        }

        //判断该级是否有上级通知
        Boolean aBoolean = gridHelper.checkIfExistSuperiorNotice(gridRegionInfoDtos);
        if (Boolean.FALSE.equals(aBoolean)) {
            Page<GridNoticeRelationDto> page = new Page<>(request.getPageNo(), request.getPageSize(), 0, Collections.emptyList());
            return Response.<Page<GridNoticeRelationDto>>ok().wrap(page);
        }

        List<String> sourceIds = gridRegionInfoDtos.stream().map(GridRegionInfoDto::getCode).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(sourceIds)) {
            request.put(LambdaUtil.getFieldName(GridNoticeRelationDto::getSourceType), gridRegionInfoDtos.get(0).getLevel());
            request.put(GridConstant.SOURCE_IDS, sourceIds);
        }

        int total = gridNoticeRelationService.queryTotal(request.getParams());

        List<GridNoticeRelationDto> list = null;
        if (total > 0) {
            list = gridNoticeRelationService.queryList(request.getParams());
            list.forEach(gridNoticeRelationDto -> {
                GridNoticeDto noticeDto = gridNoticeService.selectById(gridNoticeRelationDto.getGridNoticeId());
                if (noticeDto != null) {
                    gridNoticeRelationDto.setGridNotice(noticeDto);
                    gridNoticeRelationDto.setParentGridRegionInfo(gridHelper.packRegionInfo(noticeDto.getCreatorLevel(), noticeDto.getCreatorUniqueFlag()));
                }
            });
        } else {
            list = new ArrayList<>();
        }

        Page<GridNoticeRelationDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<GridNoticeRelationDto>>ok().wrap(page);
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping("noticeInfo")
    @Operation(summary = "查询通知公告单条记录")
    public Response<GridNoticeRelationDto> info(@Parameter(description = "通知公告Id,GridNoticeRelation的ID") @RequestParam Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (gridNoticeRelationService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        GridNoticeRelationDto gridNoticeRelationDto = gridNoticeRelationService.selectById(id);
        GridNoticeDto noticeDto = gridNoticeService.selectById(gridNoticeRelationDto.getGridNoticeId());
        gridNoticeRelationDto.setGridNotice(noticeDto);
        if (noticeDto != null) {
            gridNoticeRelationDto.setParentGridRegionInfo(gridHelper.packRegionInfo(noticeDto.getCreatorLevel(), noticeDto.getCreatorUniqueFlag()));
        }

        //更新已读状态
        if (SystemConstants.NO.equals(gridNoticeRelationDto.getReadStatus())) {
            gridNoticeRelationDto.setReadStatus(SystemConstants.YES);
            gridNoticeRelationService.updateById(gridNoticeRelationDto);
        }

        return Response.<GridNoticeRelationDto>ok().wrap(gridNoticeRelationDto);
    }

    /**
     * 1.后台创建事件统计分析柱状图
     * 2.智能发现事件统计分析
     * 处理中
     * 待办结
     * 已办结
     * 已驳回
     * 已逾期
     */
    @GetMapping("gridEventCreatedCount")
    @Operation(summary = "后台创建事件统计分析柱状图")
    public Response<CommonCountResp> gridEventCreatedCount(
            @Parameter(description = "时:HOUR 日：DAY 周：MONTH 月：MONTH 默认按日")
            @RequestParam(required = false, defaultValue = StatisticsConstants.TIME_RANGE_BY_DAY) String type,
            @Parameter(description = "来源类型1后台创建2智能发现") @RequestParam(required = false) String sourceTypeFlag
    ) {

        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());

        Map<String, Object> sysCreatedParams = gridHelper.getSysCreatedParams(request.getParams());
        //返回空数据
        if (MapUtils.isEmpty(sysCreatedParams)) {
            CommonCountResp commonCountResp = new CommonCountResp();
            List<String> xData = new ArrayList<>();
            List<Integer> yData = new ArrayList<>();

            for (GridConstant.GridEventRecordStatus value : GridConstant.GridEventRecordStatus.values()) {
                xData.add(SysCodeUtils.easyToGetName(SysCodeKeyConstants.GRID_EVENT_RECORD_STATUS, String.valueOf(value.getStatus())));
                yData.add(0);
            }
            commonCountResp.setXData(xData.toArray(new String[0]));
            commonCountResp.setYData(new CommonCountResp.DataInfo[]{
                    new CommonCountResp.DataInfo("数量", yData.toArray(new Integer[0]))
            });
            return Response.<CommonCountResp>ok().wrap(commonCountResp);
        }

        //获取日期
        Pair<String, String> startAndEndTime = gridHelper.getStartAndEndTime(type);

        String finalStartDate = startAndEndTime.getLeft();
        String finalEndDate = startAndEndTime.getRight();

        List<GridEventStatusCountResp> countResp = new CopyOnWriteArrayList<>();
        List<CompletableFuture<GridEventStatusCountResp>> futures = new ArrayList<>();

        for (GridConstant.GridEventRecordStatus value : GridConstant.GridEventRecordStatus.values()) {
            CompletableFuture<GridEventStatusCountResp> gridEventStatusCountResp = CompletableFuture.supplyAsync(
                            () -> {
                                Map<String, Object> params = new HashMap<>(sysCreatedParams);
                                //设置日期
                                params.put(GridConstant.EVENT_CREATE_DATE_SLOT_KEY_PAIR.getLeft(), finalStartDate);
                                params.put(GridConstant.EVENT_CREATE_DATE_SLOT_KEY_PAIR.getRight(), finalEndDate);
                                params.put(LambdaUtil.getFieldName(GridEventRecordDto::getStatus), value.getStatus());

                                return new GridEventStatusCountResp(gridEventRecordService.queryTotal(params), value.getStatus()
                                        , SysCodeUtils.easyToGetName(SysCodeKeyConstants.GRID_EVENT_RECORD_STATUS, String.valueOf(value.getStatus())));
                            }, executorService)
                    .exceptionally(e -> {
                        log.error(e.getMessage());
                        return new GridEventStatusCountResp(0, value.getStatus()
                                , SysCodeUtils.easyToGetName(SysCodeKeyConstants.GRID_EVENT_RECORD_STATUS, String.valueOf(value.getStatus())));
                    }).whenComplete((rsp, throwable) -> {
                        //添加到list
                        countResp.add(rsp);
                        if (throwable != null) {
                            log.info(throwable.getMessage());
                        }
                    });
            futures.add(gridEventStatusCountResp);
        }
        //阻塞
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();

        CommonCountResp commonCountResp = new CommonCountResp();
        List<String> xData = new ArrayList<>();
        List<Integer> yData = new ArrayList<>();

        Map<Byte, GridEventStatusCountResp> collect = countResp.stream().collect(Collectors.toMap(GridEventStatusCountResp::getStatus, Function.identity(), (key1, key2) -> key2));
        for (GridConstant.GridEventRecordStatus value : GridConstant.GridEventRecordStatus.values()) {
            GridEventStatusCountResp resp = collect.get(value.getStatus());
            if (resp != null) {
                xData.add(resp.getName());
                yData.add(resp.getCount());
            }
        }

        commonCountResp.setXData(xData.toArray(new String[0]));

        commonCountResp.setYData(new CommonCountResp.DataInfo[]{
                new CommonCountResp.DataInfo("数量", yData.toArray(new Integer[0]))
        });

        return Response.<CommonCountResp>ok().wrap(commonCountResp);

    }


    /**
     * 1.网格上报事件统计分析
     * 处理中
     * 待办结
     * 已办结
     * 已驳回
     * 已逾期
     */
    @GetMapping("fromGridCount")
    @Operation(summary = "网格上报统计分析柱状图")
    public Response<CommonCountResp> fromGridCount(
            @Parameter(description = "时:HOUR 日：DAY 周：MONTH 月：MONTH 默认按日")
            @RequestParam(required = false, defaultValue = StatisticsConstants.TIME_RANGE_BY_DAY) String type,
            @Parameter(description = "下属区域code") @RequestParam(required = false) Long regionCode
    ) {

        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());

        Map<String, Object> gridReportParams = gridHelper.getGridReportParams(request.getParams());
        //返回空数据
        if (MapUtils.isEmpty(gridReportParams)) {
            CommonCountResp commonCountResp = new CommonCountResp();
            List<String> xData = new ArrayList<>();
            List<Integer> yData = new ArrayList<>();

            for (GridConstant.GridEventRecordStatus value : GridConstant.GridEventRecordStatus.values()) {
                xData.add(SysCodeUtils.easyToGetName(SysCodeKeyConstants.GRID_EVENT_RECORD_STATUS, String.valueOf(value.getStatus())));
                yData.add(0);
            }
            commonCountResp.setXData(xData.toArray(new String[0]));
            commonCountResp.setYData(new CommonCountResp.DataInfo[]{
                    new CommonCountResp.DataInfo("数量", yData.toArray(new Integer[0]))
            });

            return Response.<CommonCountResp>ok().wrap(commonCountResp);
        }

        //获取日期
        Pair<String, String> startAndEndTime = gridHelper.getStartAndEndTime(type);

        String finalStartDate = startAndEndTime.getLeft();
        String finalEndDate = startAndEndTime.getRight();

        List<GridEventStatusCountResp> countResp = new CopyOnWriteArrayList<>();
        List<CompletableFuture<GridEventStatusCountResp>> futures = new ArrayList<>();

        for (GridConstant.GridEventRecordStatus value : GridConstant.GridEventRecordStatus.values()) {
            CompletableFuture<GridEventStatusCountResp> gridEventStatusCountResp = CompletableFuture.supplyAsync(
                            () -> {
                                Map<String, Object> paramCopy = new HashMap<>(gridReportParams);
                                //设置日期
                                paramCopy.put(GridConstant.EVENT_CREATE_DATE_SLOT_KEY_PAIR.getLeft(), finalStartDate);
                                paramCopy.put(GridConstant.EVENT_CREATE_DATE_SLOT_KEY_PAIR.getRight(), finalEndDate);
                                paramCopy.put(LambdaUtil.getFieldName(GridEventRecordDto::getStatus), value.getStatus());

                                return new GridEventStatusCountResp(gridEventRecordService.queryTotal(paramCopy), value.getStatus()
                                        , SysCodeUtils.easyToGetName(SysCodeKeyConstants.GRID_EVENT_RECORD_STATUS, String.valueOf(value.getStatus())));
                            }, executorService)
                    .exceptionally(e -> {
                        log.error(e.getMessage());
                        return new GridEventStatusCountResp(0, value.getStatus()
                                , SysCodeUtils.easyToGetName(SysCodeKeyConstants.GRID_EVENT_RECORD_STATUS, String.valueOf(value.getStatus())));
                    }).whenComplete((rsp, throwable) -> {
                        //添加到list
                        countResp.add(rsp);
                        if (throwable != null) {
                            log.info(throwable.getMessage());
                        }
                    });
            futures.add(gridEventStatusCountResp);
        }

        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();

        CommonCountResp commonCountResp = new CommonCountResp();

        List<String> xData = new ArrayList<>();
        List<Integer> yData = new ArrayList<>();

        Map<Byte, GridEventStatusCountResp> collect = countResp.stream().collect(Collectors.toMap(GridEventStatusCountResp::getStatus, Function.identity(), (key1, key2) -> key2));
        for (GridConstant.GridEventRecordStatus value : GridConstant.GridEventRecordStatus.values()) {
            GridEventStatusCountResp resp = collect.get(value.getStatus());
            if (resp != null) {
                xData.add(resp.getName());
                yData.add(resp.getCount());
            }
        }
        commonCountResp.setXData(xData.toArray(new String[0]));
        commonCountResp.setYData(new CommonCountResp.DataInfo[]{
                new CommonCountResp.DataInfo("数量", yData.toArray(new Integer[0]))
        });

        return Response.<CommonCountResp>ok().wrap(commonCountResp);

    }


    /**
     * 1.网格上报事件类型占比
     * 处理中
     * 待办结
     * 已办结
     * 已驳回
     * 已逾期
     */
    @GetMapping("fromGridTypeCount")
    @Operation(summary = "网格上报统计分析柱状图")
    public Response<CommonPieResp> fromGridTypeCount(
            @Parameter(description = "时:HOUR 日：DAY 周：MONTH 月：MONTH 默认按日")
            @RequestParam(required = false, defaultValue = StatisticsConstants.TIME_RANGE_BY_DAY) String type,
            @Parameter(description = "下属网格code") @RequestParam(required = false) Long regionCode,
            @Parameter(description = "一级事件ID") @RequestParam(required = false) Long eventPrimaryId
    ) {

        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());

        List<GridEventTypeCountResp> gridEventTypeCountResps;
        //查询所有的一级事件 如果为-1为全部一级事件
        if (eventPrimaryId == null) {
            Map<String, Object> eventParams = Request.parseParams(httpServletRequest);
            super.fillAuthorityData(eventParams);
            List<GridPrimaryEventDto> gridPrimaryEventDtos = gridPrimaryEventService.queryList(eventParams);
            gridEventTypeCountResps = gridPrimaryEventDtos.stream().map(gridPrimaryEventDto -> {
                GridEventTypeCountResp resp = new GridEventTypeCountResp();
                resp.setEventId(gridPrimaryEventDto.getId());
                resp.setName(gridPrimaryEventDto.getName());
                resp.setCount(0);
                return resp;
            }).collect(Collectors.toList());
        } else {
            //查询所有的二级事件
            Map<String, Object> eventParams = Request.parseParams(httpServletRequest);
            super.fillAuthorityData(eventParams);
            eventParams.put(LambdaUtil.getFieldName(GridSecondaryEventDto::getPrimaryEventId), eventPrimaryId);
            List<GridSecondaryEventDto> gridSecondaryEventDtos = gridSecondaryEventService.queryList(eventParams);
            gridEventTypeCountResps = gridSecondaryEventDtos.stream().map(gridPrimaryEventDto -> {
                GridEventTypeCountResp resp = new GridEventTypeCountResp();
                resp.setEventId(gridPrimaryEventDto.getId());
                resp.setName(gridPrimaryEventDto.getName());
                resp.setCount(0);
                return resp;
            }).collect(Collectors.toList());
        }

        Map<String, Object> gridReportParams = gridHelper.getGridReportParams(request.getParams());
        if (MapUtils.isEmpty(gridReportParams)) {
            List<CommonPieResp.PieInfo> eventList = new ArrayList<>();
            for (GridEventTypeCountResp resp : gridEventTypeCountResps) {
                eventList.add(new CommonPieResp.PieInfo(resp.getName(), 0d));
            }
            CommonPieResp commonCountResp = new CommonPieResp();
            commonCountResp.setTotal((double) 0);
            commonCountResp.setPieData(eventList.toArray(new CommonPieResp.PieInfo[0]));
            return Response.<CommonPieResp>ok().wrap(commonCountResp);
        }
        //获取日期
        Pair<String, String> startAndEndTime = gridHelper.getStartAndEndTime(type);

        String finalStartDate = startAndEndTime.getLeft();
        String finalEndDate = startAndEndTime.getRight();

        List<CompletableFuture<Void>> futures = new ArrayList<>();

        for (GridEventTypeCountResp resp : gridEventTypeCountResps) {
            CompletableFuture<Void> gridEventStatusCountResp = CompletableFuture.runAsync(
                    () -> {
                        Map<String, Object> paramCopy = new HashMap<>(gridReportParams);
                        //设置日期
                        paramCopy.put(GridConstant.EVENT_CREATE_DATE_SLOT_KEY_PAIR.getLeft(), finalStartDate);
                        paramCopy.put(GridConstant.EVENT_CREATE_DATE_SLOT_KEY_PAIR.getRight(), finalEndDate);
                        if (eventPrimaryId == null) {
                            paramCopy.put(LambdaUtil.getFieldName(GridEventRecordDto::getEventPrimaryId), resp.getEventId());
                        } else {
                            paramCopy.put(LambdaUtil.getFieldName(GridEventRecordDto::getEventSecondaryId), resp.getEventId());
                        }
                        resp.setCount(gridEventRecordService.queryTotal(paramCopy));
                    }, executorService);
            futures.add(gridEventStatusCountResp);
        }
        //阻塞
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
        //处理查询到的数据
        long count = gridEventTypeCountResps.stream().mapToInt(GridEventTypeCountResp::getCount).sum();
        List<CommonPieResp.PieInfo> eventList = new ArrayList<>();
        for (GridEventTypeCountResp resp : gridEventTypeCountResps) {
            eventList.add(new CommonPieResp.PieInfo(resp.getName(), Double.valueOf(resp.getCount())));
        }
        CommonPieResp commonCountResp = new CommonPieResp();
        commonCountResp.setTotal((double) count);
        commonCountResp.setPieData(eventList.toArray(new CommonPieResp.PieInfo[0]));
        return Response.<CommonPieResp>ok().wrap(commonCountResp);
    }


    /**
     * 1.逾期率统计分析
     */
    @GetMapping("overdueCount")
    @Operation(summary = "逾期率统计分析")
    public Response<CommonPieResp> overdueCount(
            @Parameter(description = "时:HOUR 日：DAY 周：MONTH 月：MONTH 默认按日")
            @RequestParam(required = false, defaultValue = StatisticsConstants.TIME_RANGE_BY_DAY) String type
    ) {
        CommonPieResp commonCountResp = new CommonPieResp();
        commonCountResp.setTotal(100d);
        CommonPieResp.PieInfo overduePieInfo = new CommonPieResp.PieInfo("逾期", 0d);
        CommonPieResp.PieInfo notOverduePieInfo = new CommonPieResp.PieInfo("未逾期", 100d);

        commonCountResp.setPieData(new CommonPieResp.PieInfo[]{overduePieInfo, notOverduePieInfo});

        //查看当前所处区域等级
        List<GridRegionInfoDto> gridRegionInfoDtos = gridHelper.queryRegionInfoByGroupId(SessionHolder.getSysUser().getGroupId());
        if (CollectionUtils.isEmpty(gridRegionInfoDtos)) {
            return Response.<CommonPieResp>ok().wrap(commonCountResp);
        }

        Map<String, Object> params = new HashMap<>();
        params.put(LambdaUtil.getFieldName(GridEventRecordDto::getTenantId), SessionHolder.getSysUser().getTenantId());

        //如果是小区

        if (GridConstant.RegionLevel.DISTRICT_LEVEL.getLevel().equals(gridRegionInfoDtos.get(0).getLevel())) {
            params.put(LambdaUtil.getFieldName(GridEventRecordDto::getDistrictCode), gridRegionInfoDtos.get(0).getCode());
        } else if (GridConstant.RegionLevel.STREET_LEVEL.getLevel().equals(gridRegionInfoDtos.get(0).getLevel())) {
            //如果是街道
            params.put(LambdaUtil.getFieldName(GridEventRecordDto::getStreetCode), gridRegionInfoDtos.get(0).getCode());
        } else if (GridConstant.RegionLevel.VILLAGE_LEVEL.getLevel().equals(gridRegionInfoDtos.get(0).getLevel())) {
            //如果是区
            List<String> villageIs = gridRegionInfoDtos.stream().map(GridRegionInfoDto::getCode).collect(Collectors.toList());
            params.put(GridConstant.VILLAGE_IDS, villageIs);
        } else {
            return Response.<CommonPieResp>ok().wrap(commonCountResp);
        }

        //获取日期
        Pair<String, String> startAndEndTime = gridHelper.getStartAndEndTime(type);

        String finalStartDate = startAndEndTime.getLeft();
        String finalEndDate = startAndEndTime.getRight();

        AtomicInteger overdueCount = new AtomicInteger();
        AtomicInteger total = new AtomicInteger();

        CompletableFuture<Void> overdueFuture = CompletableFuture.runAsync(
                () -> {
                    Map<String, Object> paramCopy = new HashMap<>(params);
                    //设置日期
                    paramCopy.put(GridConstant.EVENT_CREATE_DATE_SLOT_KEY_PAIR.getLeft(), finalStartDate);
                    paramCopy.put(GridConstant.EVENT_CREATE_DATE_SLOT_KEY_PAIR.getRight(), finalEndDate);
                    paramCopy.put(LambdaUtil.getFieldName(GridEventRecordDto::getStatus), GridConstant.GridEventRecordStatus.EXPIRED.getStatus());

                    overdueCount.set(gridEventRecordService.queryTotal(paramCopy));
                }, executorService);

        CompletableFuture<Void> totalFuture = CompletableFuture.runAsync(
                () -> {
                    Map<String, Object> paramCopy = new HashMap<>(8);
                    paramCopy.putAll(params);
                    //设置日期
                    paramCopy.put(GridConstant.EVENT_CREATE_DATE_SLOT_KEY_PAIR.getLeft(), finalStartDate);
                    paramCopy.put(GridConstant.EVENT_CREATE_DATE_SLOT_KEY_PAIR.getRight(), finalEndDate);

                    total.set(gridEventRecordService.queryTotal(paramCopy));
                }, executorService);

        //阻塞
        CompletableFuture.allOf(overdueFuture, totalFuture).join();

        if (total.get() != 0) {
            //逾期率
            BigDecimal divide = BigDecimal.valueOf(overdueCount.get()).multiply(BigDecimal.valueOf(100)).divide(new BigDecimal(total.get()), 2, RoundingMode.HALF_UP);
            overduePieInfo.setValue(divide.doubleValue());
            //未逾期率
            BigDecimal notOverdueRate = BigDecimal.valueOf(100).add(divide.negate()).setScale(2, RoundingMode.HALF_UP);
            notOverduePieInfo.setValue(notOverdueRate.doubleValue());
        }

        commonCountResp.setPieData(new CommonPieResp.PieInfo[]{overduePieInfo, notOverduePieInfo});

        return Response.<CommonPieResp>ok().wrap(commonCountResp);
    }

}
